$(function () {
    init_left_groupList();
    init_mycustomer();
    $("body").on('click','[data-stopPropagation]',function (e) {e.stopPropagation();});
});
/**初始化左侧客户分组*/
function init_left_groupList() {
    $.post(ctx+"myCustomer/selectGroupList",{},function (r) {
        if(r.code===0){
            $("#moveGroupId").empty();
            var data = r.data;
            $("#mg-left-group").empty().append('<li class="height-25 f-s-12" onclick="selectGroup(this);"  uuid="">' +
                '<a href="javascript:;" ><i class="fa fa-flag fa-fw m-r-5"></i> &nbsp;全部</a></li>')
                .append('<li class="height-25 f-s-12" onclick="selectGroup(this);"  uuid="nogroup">' +
                '<a href="javascript:;" ><i class="fa fa-flag fa-fw m-r-5"></i> &nbsp;未分组</a></li>');

            $.each(data,function (index, val) {
               var li ='<li class="height-25 f-s-12" onclick="selectGroup(this);"  uuid="'+val.cGroupUuid+'">' +
                   '<a href="javascript:;" ><i class="fa fa-flag fa-fw m-r-5"></i> '+val.cGroupName+'</a></li>';
               $("#mg-left-group").append(li);
               var ul = '<li onclick="addCustomerGroup(this);" uuid="'+val.cGroupUuid+'"><a href="javascript:;" class="p-r-5" >' +
                   '<i class="fa fa-flag fa-fw m-r-5"></i> '+val.cGroupName+'</a></li>';
               $("#moveGroupId").append(ul);
            });
        }else{
            $JuXue.n_danger("加载客户分组失败");
        }
    });
    /**初始化标签得内容**/
    $.post(ctx+"saleConfig/selectSaletag",{},function (r) {
        if (r.code == 0){
            var data = r.msg;
            $.each(data,function (index,val) {
               var div =  $(' <div class="text-left border-bottom-1"></div>');
               var fistdiv  ='<div class="border-bottom-1 p-t-3"><div class="checkbox m-0"><span class="m-r-15 m-l-5">'+val.parent.tagGroupName+'</span>\n' +
               '<label><input type="checkbox" style="margin: 1px -20px 0px;" />不包含 <input type="hidden" value='+val.parent.tagSelect+' /></label></div></div>';
               div.append(fistdiv);
               var cc = $("<div class='m-t-5 p-3 text-left'><input type='hidden' value="+val.parent.tagSelect+" /></div>");
               $.each(val.children,function (i,v) {
                   cc.append('<button type="button" onclick="selectTagIscheck(this)" data-id="'+v.tagUuids+'" ' +
                       'class="btn btn-xs btn-link width-100 m-l-5 p-2 m-b-5 f-s-12 border-solid-g">'+v.tagName+'</button>');
               });
               div.append(cc);
               $("#selectTag").append(div);
            });
        }else{
            $JuXue.n_danger(r.msg);
        }
    });
    /**初始化人员选择**/
    $.post(ctx+"dept/getUseeAndDepttree",{},function (r) {
        var array  = r.msg;
        $("#selectUser").jstree({
            "core": {
                "multiple": false,"data":array, "icon":false, "themes":{"icons":false}
            },
            "checkbox" : {"keep_selected_style" : false},
            "plugins" : [ "wholerow", "checkbox" ]
        });
    });

}

/**初始化我的客户**/
function init_mycustomer(){
    var settings = {
        url: ctx + "myCustomer/getMyCustomerList",
        pageSize: 15,
        sortable: true,                     //是否启用排序
        sortOrder: "desc",                 //排序方式
        sortName: 'recordtime',//排序字段
        onLoadSuccess: function () {
            $("[data-toggle='tooltip']").tooltip();//初始化 沟通方式的鼠标
        },
        queryParams: function(params) {
            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                dataid:     $("#loadTabId").val(), //左侧区分/组
                stage:      $("#slectcusStage").val(),//客户阶段
                groups:     $("#selectFroup").val(),  //分组
                otherLabel: $("#selecttagOnter").val(),//其他标签
                label:      $("#selectContion").val(),//包含标签
                notLabel:   $("#selectNotContion").val(),//不包含标签
                timeType:   $("#timeSelect").val(), //时间类型
                beforeTime: $("#starttime").val(), //开始时间
                afterTime:  $("#endtime").val(),//结束时间
                toolType :  $("#typeTool").val(),//类型
                toolTong :  $("#tongTool").val(), //通讯
                types    :  $("#SourType").val(),//资源类型
                plan     :  $("#selectPlanId").val(), //销售计划
                receiver :  $("#recrveUser").val(),//人员筛选
                searchType: $("#searchType").val(),  //综合查询类型
                searchValue :$("#searchValue").val() //综合查询的值
            };
        },
        columns: [{
            checkbox: true
        }, {
            field: 'nickname',
            title: '客户名称',
            width: 200,
            clickToSelect:false,
            formatter:function (value, row, index) {
                return "<a href='javascript:void(0)' onclick='viewMycusDetail(this);' uuid = '"+row.uuid+"' data-type='"+row.types+"' data-id='"+row.id+"'>"+value+"</a>";
            }
        }, {
            field: 'types',
            title: '资源类型',
            formatter:function (value, row, index) {
                var typename = "";
                if(value=="1"){typename = "推广资源类";
                }else if(value=="2"){typename = "网校资源类";
                }else if(value=="3"){typename = "大资源类";
                }else if(value=="5"){typename = "AI资源类";
                }else{typename = "个人录入";}
                return typename;
            }
        }, {
            field: 'mobile',
            title: '沟通方式',
            clickToSelect:false,
            formatter:function (value,row,index) {
                var qq = row.qq;var wechat = row.wechat;
                var monile = "";var utype = row.types;
                var uid = row.id;var cn = row.nickname;
                if (value != null && value != ""){
                    monile = '<a href="#" data-toggle="tooltip" data-placement="top" title="'+value+'" utype="'+utype+'" uid="'+uid+'" cn = "'+cn+'" onclick="makePhoneCall(this)" phone="'+value+'" ><i class="fa fa-phone  text-success m-3"></i></a>';
                }
                var qqlabel  = "";
                if (qq!=null && qq != ""){
                    qqlabel = '<a href="#" data-toggle="tooltip" data-placement="top" title="'+qq+'"><i class="fa fa-qq  text-success m-3"></i></a>';
                }
                var wechatlabel = "";
                if (wechat!=null && wechat != ""){
                    wechatlabel = '<a href="#" data-toggle="tooltip" data-placement="top" title="'+wechat+'"><i class="fa fa-weixin  text-success m-3"></i></a>';
                }
                return monile+qqlabel+wechatlabel;
            }
        }, {
            field: 'label',
            title: '客户标签',
            width: '20%',
            formatter:function (value, row, index) {
                if (value !=null){
                    var label = value.split(",");
                    var str = "";
                    $.each(label,function (i,v) {
                        str += '<span type="button" class="btn btn-xs btn-link m-l-3 m-b-3  f-s-10 border-solid-g">'+v+'</span>';
                    });
                    return str;
                }
                return '-';
            }
        }, {
            field: 'distributor',
            title: '分配人'
        }, {
            field: 'recordtime',
            title: '最近动态',
            sortable: true,
            formatter:function (value, row, index) {
                var time = row.recordtime;var record = row.record;
                return time+"<br/>"+record;
            }
        }, {
            field: 'createtime',
            title: '客户创建时间',
            sortable:true,
            formatter:function (value, row, index) {
                return value.substring(0,10);
            }
        }],
        onClickCell:function(field, value, row, $element){
            if(field == "nickname" || field == "mobile"){
                return ;
            }else{
                $(".theme-panel").addClass("active");
                $("#selectTheme").show();
                var selected = $("#myEmpTable").bootstrapTable('getSelections');
                var selected_length = selected.length;
                $("#sutomeSelect").text(selected_length+1);
                controllMuenuStatus();
            }
        },
        onUncheck:function (row,ele) {
            var selected = $("#myEmpTable").bootstrapTable('getSelections');
            var selected_length = selected.length;
            if (!selected_length) {
                $(".theme-panel").removeClass("active");
                $("#selectTheme").hide();
            }
            $("#sutomeSelect").text(selected_length+1);
            controllMuenuStatus();
        },
        onCheck:function (row,ele) {
            var selected = $("#myEmpTable").bootstrapTable('getSelections');
            var selected_length = selected.length;
            if (!selected_length) {
                $(".theme-panel").removeClass("active");
                $("#selectTheme").hide();
            }else{
                $(".theme-panel").addClass("active");
                $("#selectTheme").show();controllMuenuStatus();
            }
            $("#sutomeSelect").text(selected_length);
        },
        onUncheck:function (rows) {
            var selected = $("#myEmpTable").bootstrapTable('getSelections');
            var selected_length = selected.length;
            if (!selected_length) {
                $(".theme-panel").removeClass("active");
                $("#selectTheme").hide();
            }else{
                $(".theme-panel").addClass("active");
                $("#selectTheme").show();controllMuenuStatus();
            }
            $("#sutomeSelect").text(selected_length);
        },
        onCheckAll:function (rows) {
            $(".theme-panel").addClass("active");
            $("#selectTheme").show();controllMuenuStatus();
            $("#sutomeSelect").text(rows.length);
        },
        onUncheckAll:function (rows) {
            $(".theme-panel").removeClass("active");
            $("#selectTheme").hide();
        }
    };
    $JuXue.initTable('myEmpTable', settings);

    /**客户阶段**/
    $.post(ctx+"saleConfig/initTrackTable",function (r) {
        var data = r.data;
        var defaultbtn = '<button type="button" class="btn btn-link m-l-10 p-3 btn-primary" onclick="selectTrack(this);" data="">不限</button>';
        $("#customeTrack").empty().append(defaultbtn);
        $.each(data,function (index,val) {
            var btn = '<button type="button" class="btn btn-link m-l-10 p-3" onclick="selectTrack(this);" data="'+val.saleUuid+'">'+val.saleName+'</button>';
            $("#customeTrack").append(btn)
        });
    });

    /**初始化时间选择**/
    $("#select_time span").html(moment().subtract("days",29).format("YYYY-MM-DD")+" - "+moment().format("YYYY-MM-DD"));
    $('#select_time').daterangepicker({
        timePicker: true, //显示时间
        timePicker24Hour: true, //时间制
        timePickerSeconds: true, //时间显示到秒
        startDate: moment().hours(0).minutes(0).seconds(0), //设置开始日期
        endDate: moment(new Date()), //设置结束器日期
        maxDate: moment(new Date()), //设置最大日期
        "opens": "center",
        ranges: {
            '今天': [moment(), moment()],'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '上周': [moment().subtract(6, 'days'), moment()],
            '前30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        showWeekNumbers: true,
        locale: {
            format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
            applyLabel: '确定', //确定按钮文本
            cancelLabel: '取消', //取消按钮文本
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月'
            ],
            firstDay: 1
        },
    }).on('apply.daterangepicker', function(ev, picker) {
        var starttime = picker.startDate.format('YYYY-MM-DD');
        var endtime = picker.endDate.format('YYYY-MM-DD');
        $("#select_time span").html(starttime+" - "+endtime);
        $("#starttime").val(starttime);
        $("#endtime").val(endtime);
        $JuXue.refreshTable("myEmpTable");
    });
}

/**控制各个菜单得状态**/
function controllMuenuStatus() {
    var loadTab = $("#loadTabId").val();
    if (loadTab == "tome"){
        //共享给我得客户 (没有 放弃 共享，转让，领取 和移动分组得权限)
        $("#fangqi").hide();$("#gongxiang").hide();$("#zhuanrang").hide();$("#lingqu").hide();$("#fenpei").hide();
        $("#fenzu").hide();$("#xiaoshoujihua").show();$("#shezhibiaoqian").show();$("#daochu").show();$("#gongsiLingqu").hide();
    }else if (loadTab == "meto") {
        //我分享得客户
        $("#fangqi").show();$("#gongxiang").show();$("#zhuanrang").show();$("#lingqu").hide();$("#fenpei").hide();
        $("#fenzu").show();$("#xiaoshoujihua").show();$("#shezhibiaoqian").show();$("#daochu").show();$("#gongsiLingqu").hide();
    }else if (loadTab == "allsea") {
        //公司大公海
        $("#fangqi").hide();$("#gongxiang").hide();$("#zhuanrang").hide();$("#lingqu").hide();$("#fenpei").show();
        $("#fenzu").hide();$("#xiaoshoujihua").hide();$("#shezhibiaoqian").hide();$("#daochu").show();$("#gongsiLingqu").show();
    }else if (loadTab =="deptsea"){
        //部门公海
        $("#fangqi").hide();$("#gongxiang").hide();$("#zhuanrang").hide();$("#lingqu").show();$("#fenpei").hide();
        $("#fenzu").hide();$("#xiaoshoujihua").hide();$("#shezhibiaoqian").hide();$("#daochu").show();$("#gongsiLingqu").hide();
    }else{
        //我得客户
        $("#fangqi").show();$("#gongxiang").show();$("#zhuanrang").show();$("#lingqu").hide();$("#fenpei").hide();
        $("#fenzu").show();$("#xiaoshoujihua").show();$("#shezhibiaoqian").show();$("#daochu").show();$("#gongsiLingqu").hide();
    }
}
/**选择标签**/
function selectTagIscheck(btn) {
    var $parentcheck  = $(btn).parent();
    var isMultiInput = $parentcheck.children("input:first-child").val();
    if (isMultiInput == "1"){
        var ishave = $(btn).hasClass("btn-primary");
        if (ishave) {$(btn).removeClass("btn-primary");
        }else{$(btn).addClass("btn-primary");}
    }else{
        //单选
        var ishave = $(btn).hasClass("btn-primary");
        if (ishave) {$parentcheck.find("button").each(function () {$(this).removeClass("btn-primary");});}else{
            $parentcheck.find("button").each(function () {$(this).removeClass("btn-primary");});
            $(btn).addClass("btn-primary");
        }
    }
}
/**确定标签**/
function labelSelectSure() {
    var div = $("#selectTag").children("div");
    //包含
    var selectids = new Array();
    var selectnames = new Array();
    //不包含
    var notselectids = new Array();
    var notselectnames = new Array();
    $.each(div,function (index,val) {
        var isChecked = $(this).find("input[type='checkbox']").eq(0).is(':checked');
        if (isChecked) {
            //如果选中 则表示不包含
            var btn = $(this).find("button");
            $.each(btn,function () {
                var isSelect = $(this).hasClass("btn-primary");
                if (isSelect){
                    var notselectid = $(this).attr("data-id");
                    var notselectname = $(this).text();
                    notselectids.push(notselectid);notselectnames.push(notselectname);
                }
            });
        }else{
            //包含
            var btn = $(this).find("button");
            $.each(btn,function () {
                var isSelect = $(this).hasClass("btn-primary");
                if (isSelect){
                    var selectid = $(this).attr("data-id");
                    var selectname = $(this).text();
                    selectids.push(selectid);selectnames.push(selectname);
                }
            });
        }
    });
    var length = selectids.length+notselectids.length;
    if(length > 5){$JuXue.n_danger("标签选择不能大于5个");return ;}
    else {if (length <= 0){$("#otherselect").show();}else{$("#otherselect").hide();}}
    $("#drownSelect").empty();
    $.each(selectnames,function (i,v) {
        $("#drownSelect").append('<a type="button" class="btn btn-link m-l-10 p-3 f-s-10 btn-primary ">'+v+'</a>');
    });
    $.each(notselectnames,function (i,v) {
        $("#drownSelect").append('<a type="button" class="btn btn-link m-l-10 p-3 f-s-10 btn-default">'+v+'</a>');
    });
    $("#labelselect").removeClass("open");
    $("#selectContion").val(selectids.join(","));
    $("#selectNotContion").val(notselectids.join(","));
    $JuXue.refreshTable('myEmpTable');
}
/**点击其他动态选项卡**/
function selectTagByOther(btn) {
    $("#otherselect").find("a").each(function () {$(this).removeClass("btn-primary");});
    $(btn).addClass("btn-primary");
    //动态加载
    var project = $(btn).attr("data-click");
    $("#selecttagOnter").val(project);
    $JuXue.refreshTable('myEmpTable');
}
/**点击切换客户阶段**/
function selectTrack(btn) {
    $("#customeTrack").find("button").each(function () {$(this).removeClass("btn-primary");});
    $(btn).addClass("btn-primary");
    //动态加载
    var project = $(btn).attr("data");
    $("#slectcusStage").val(project);
    $JuXue.refreshTable("myEmpTable");
}
/**导出客户资料**/
function exportCustomerInfoConfire() {
    var ids = $("#myEmpTable").bootstrapTable("getSelections");
    var ids_arr = "";
    if (!ids.length) {$JuXue.n_warning("请勾选需要导出的客户信息！");return;}
    for (var i = 0; i < ids.length; i++) {
        ids_arr += ids[i].uuid;
        if (i !== (ids.length - 1)) ids_arr += ",";
    }
    $.post(ctx+"myCustomer/exportDetailforExcel",{"keyids":ids_arr},function(r){
        if (r.code === 0) {
            window.open("file/download?fileName=" + r.msg + "&delete=" + true);
        } else {$JuXue.n_warning(r.msg);}
    });
}
/**选择用户**/
function selectUserGruop(){
    $('#userSelGroger').removeClass('open');
    var data = $('#selectUser').jstree(true).get_selected(true);//获得整个树
    if (data.length == 1){
        var userid = data[0].id;
        $("#recrveUser").val(userid);var username  = data[0].text;
        $("#selectuse").text("用户选择: "+username);
    }else{$("#selectuse").text("用户筛选");$("#recrveUser").val("");}
    $JuXue.refreshTable("myEmpTable");
}
/**重置用户选择**/
function selectUserReset(){
    $('#userSelGroger').removeClass('open');
    $('#selectUser').jstree(true).deselect_all(true);
    $("#selectuse").text("用户筛选");$("#recrveUser").val("");
    $JuXue.refreshTable("myEmpTable");
}

/**打电话插件**/
function makePhoneCall(btn) {
    var itype = $(btn).attr("utype");
    var uid =  $(btn).attr("uid");
    var cn = $(btn).attr("cn");
    var phone = $(btn).attr("phone");
    $("#suatomename").val(cn);
    $("#dialcode").val(phone);
    sessionStorage.setItem("typeDia","1");
    $("#cus_phone_uid").val(uid);
    $("#cus_uid_type").val(itype);

    $("#phone-modal").modal('show').draggable();
    $('#minute_show').html('<s></s>00 分');
    $('#second_show').html('<s></s>00 秒');

    $("#dialcodeNumid").show();


}
